﻿namespace MicroCloud.Utils
{
    /// <summary>
    /// 手机号码数据类型
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
    public class MobileNumberAttribute : DataTypeAttribute
    {
        /// <summary>
        /// 手机号正则表达式
        /// 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
        /// 联通号段: 130,131,132,145,155,156,170,171,175,176,185,186
        /// 电信号段: 133,149,153,170,173,177,180,181,189
        /// </summary>
        public const string MobileNumberRegex = @"^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))[0-9]{8}$";

        /// <summary>
        /// 初始化一个手机号码数据类型 <see cref="MobileNumberAttribute"/> 的新实例
        /// </summary>
        public MobileNumberAttribute()
            : base(DataType.PhoneNumber)
        { }

        #region 方法 - Overrides of DataTypeAttribute
        /// <summary>
        /// 检查数据字段的值是否有效
        /// </summary>
        /// <param name="value">要验证的数据字段值</param>
        /// <returns>如果指定的值有效或 null，则为 true；否则，为 false</returns>
        public override bool IsValid(object value)
        {
            if (value is string)
            {
                string input = value as string;
                if (input.IsNullOrEmpty())
                {
                    return true;
                }
                return input.IsMatch(MobileNumberRegex);
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 基于发生错误的数据字段对错误消息应用格式设置
        /// </summary>
        /// <param name="name">要包括在带有格式的消息中的名称</param>
        /// <returns>带有格式的错误消息的实例</returns>
        public override string FormatErrorMessage(string name)
        {
            return I18N.T("{0} 必须为有效的手机号码", name);
        }

        #endregion

    }

}
